package elephant.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLUtil {
	//
	public static InputStream getStringStream(String sInputString) {
		ByteArrayInputStream tInputStringStream = null;
		if (sInputString != null && !sInputString.trim().equals("")) {
			tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
		}
		return tInputStringStream;
	}
	//
	public static Map<String, String> getMapFromXML(String xmlString) throws Exception {
		// 这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		InputStream is = getStringStream(xmlString);
		Document document = builder.parse(is);

		// 获取到document里面的全部结点
		NodeList allNodes = document.getFirstChild().getChildNodes();
		Node node;
		Map<String, String> map = new HashMap<>();
		int i = 0;
		while (i < allNodes.getLength()) {
			node = allNodes.item(i);
			if (node instanceof Element) {
				map.put(node.getNodeName(), node.getTextContent());
			}
			i++;
		}
		return map;

	}
	//
	public static void main(String[] args) throws Exception {
		String input="<xml><return_code><![CDATA[SUCCESS]]></return_code>"+
		"<return_msg><![CDATA[OK]]></return_msg>"+
		"<appid><![CDATA[wxd370997aa5c4f2b1]]></appid>"+
		"<mch_id><![CDATA[1284157601]]></mch_id>"+
		"<device_info><![CDATA[APP-001]]></device_info>"+
		"<nonce_str><![CDATA[RZCB1LwIOpZwoDMZ]]></nonce_str>"+
		"<sign><![CDATA[D8612C7BCDF339E20127AB62821EF990]]></sign>"+
		"<result_code><![CDATA[SUCCESS]]></result_code>"+
		"<prepay_id><![CDATA[wx20151125171319fdf11dc2db0506589159]]></prepay_id>"+
		"<trade_type><![CDATA[APP]]></trade_type>"+
		"</xml>";
		Map<String,String> map=getMapFromXML(input);
		for(Map.Entry<String,String> e:map.entrySet()){  
            System.out.println(e.getKey()+"="+e.getValue());
        }  
	}
}
